# -*- coding: utf-8 -*-
# @Time: 2025/7/24 7:30
# @Author: foxhuty
# @File: crawling_B_video.py
# @Software: PyCharm
# @Based on python 3.10
import requests


def get_bilibili_video_info(bvid):
    # 构造API请求URL
    api_url = f"https://api.bilibili.com/x/web-interface/view?bvid={bvid}"

    # 添加请求头模拟浏览器访问
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Referer": f"https://www.bilibili.com/video/{bvid}/"
    }

    try:
        response = requests.get(api_url, headers=headers)
        response.raise_for_status()  # 检查HTTP错误
        data = response.json()
        print(data)
        print(data['code'])

        if data["code"] == 0:
            info = data["data"]
            return {
                "标题": info["title"],
                "UP主": info["owner"]["name"],
                "播放量": info["stat"]["view"],
                "弹幕量": info["stat"]["danmaku"],
                "点赞量": info["stat"]["like"],
                "投币量": info["stat"]["coin"],
                "收藏量": info["stat"]["favorite"],
                "视频时长": info["duration"],
                "发布时间": info["pubdate"]
            }
        else:
            print("API返回错误:", data["message"])
            return None

    except Exception as e:
        print("请求失败:", str(e))
        return None

# https://www.bilibili.com/video/BV1uYN1e2Em3/?spm_id_from=333.337.search-card.all.click&vd_source=416c516993c044dbe2bb6e5b56753a8a
# https://www.bilibili.com/video/BV1kSZiYtEAa?spm_id_from=333.788.player.switch&vd_source=416c516993c044dbe2bb6e5b56753a8a&p=56
# 使用示例
video_info = get_bilibili_video_info("BV1kSZiYtEAa")
if video_info:
    for key, value in video_info.items():
        print(f"{key}: {value}")
